<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="学习笔记,量化投资,Backtrader,多因子选股," />










<meta name="description" content="为了应付一个考试，停了一个多月。现在学习继续。这次要实现的是多因子选股。即通过多个因子来在股票池中选择一个或数个股票，以期获得高于市场平均水平的收益。属于量化选股的一种。主要有打分法和回归法两种。先实现最简单的打分法吧。由于我使用的是tushare获取数据，先看看能获取哪些因子。用ts.get_stock_basics()，结果是这样的:pe是市盈率，outstanding是流通股本，totals">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记85——实现量化交易经典策略:多因子选股">
<meta property="og:url" content="https://zwdnet.github.io/2020/08/24/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B085%E2%80%94%E2%80%94%E5%AE%9E%E7%8E%B0%E9%87%8F%E5%8C%96%E4%BA%A4%E6%98%93%E7%BB%8F%E5%85%B8%E7%AD%96%E7%95%A5-%E5%A4%9A%E5%9B%A0%E5%AD%90%E9%80%89%E8%82%A1/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="为了应付一个考试，停了一个多月。现在学习继续。这次要实现的是多因子选股。即通过多个因子来在股票池中选择一个或数个股票，以期获得高于市场平均水平的收益。属于量化选股的一种。主要有打分法和回归法两种。先实现最简单的打分法吧。由于我使用的是tushare获取数据，先看看能获取哪些因子。用ts.get_stock_basics()，结果是这样的:pe是市盈率，outstanding是流通股本，totals">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/58/01.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/58/02.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/58/03.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/58/04.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/58/05.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/58/06.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2020-08-24T08:00:22.000Z">
<meta property="article:modified_time" content="2020-08-30T05:52:04.000Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="Backtrader">
<meta property="article:tag" content="多因子选股">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/58/01.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2020/08/24/量化投资学习笔记85——实现量化交易经典策略-多因子选股/"/>





  <title>量化投资学习笔记85——实现量化交易经典策略:多因子选股 | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2020/08/24/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B085%E2%80%94%E2%80%94%E5%AE%9E%E7%8E%B0%E9%87%8F%E5%8C%96%E4%BA%A4%E6%98%93%E7%BB%8F%E5%85%B8%E7%AD%96%E7%95%A5-%E5%A4%9A%E5%9B%A0%E5%AD%90%E9%80%89%E8%82%A1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记85——实现量化交易经典策略:多因子选股</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-08-24T08:00:22+00:00">
                2020-08-24
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.7k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  7
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>为了应付一个考试，停了一个多月。现在学习继续。这次要实现的是多因子选股。即通过多个因子来在股票池中选择一个或数个股票，以期获得高于市场平均水平的收益。属于量化选股的一种。<br>主要有打分法和回归法两种。先实现最简单的打分法吧。<br>由于我使用的是tushare获取数据，先看看能获取哪些因子。<br>用ts.get_stock_basics()，结果是这样的:<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/58/01.png"><br>pe是市盈率，outstanding是流通股本，totals是总股本，totalAssets是总资产，liquidAssets是流动资产，fixedAssets是固定资产，reversved是公积金，esp每股收益，bvps每股净资，pb市净率，timeToMarket上市日期，undp未分利润，rev收入同比，profit利润同比，gpr毛利润，npr净利润，holders，股东人数。<br>还有获取其它数据的函数，第一次弄，先用这个吧。<br>首先排除一些股票：<br>①上市不满2年的股票。<br>②ST的股票<br>③亏损的股票。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># coding:utf-8</span></span><br><span class="line"><span class="comment"># 多因子选股实现</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> backtrader <span class="keyword">as</span> bt</span><br><span class="line"><span class="keyword">import</span> backtrader.indicators <span class="keyword">as</span> bi</span><br><span class="line"><span class="keyword">import</span> backtest</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> tushare <span class="keyword">as</span> ts</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取股票数据，进行初步筛选，返回供因子分析的股票数据。</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">getFactors</span>():</span></span><br><span class="line"><span class="comment">#    data = ts.get_stock_basics()</span></span><br><span class="line"><span class="comment">#    print(data.head())</span></span><br><span class="line"><span class="comment">#    print(len(data))</span></span><br><span class="line"><span class="comment">#    data.to_csv(&quot;stocks.csv&quot;)</span></span><br><span class="line">    data = pd.read_csv(<span class="string">&quot;stocks.csv&quot;</span>, index_col = <span class="string">&quot;code&quot;</span>)</span><br><span class="line">    <span class="comment"># 排除亏损的股票</span></span><br><span class="line">    data = data[data.npr &gt; <span class="number">0.0</span>]</span><br><span class="line">    <span class="comment"># 排除上市不满2年的</span></span><br><span class="line">    data = data[data.timeToMarket &lt;= <span class="number">20180801</span>]</span><br><span class="line">    <span class="comment"># 排除ST股票</span></span><br><span class="line">    data = data[~ data.name.<span class="built_in">str</span>.contains(<span class="string">&quot;ST&quot;</span>)]</span><br><span class="line">    <span class="comment"># print(data)</span></span><br><span class="line">    <span class="keyword">return</span> data</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    factors = getFactors()</span><br><span class="line">大概剔除了<span class="number">1</span>/<span class="number">3</span>的股票。接下来分析一下剩下的数据。</span><br><span class="line"><span class="comment"># 分析数据</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">analysis</span>(<span class="params">factors</span>):</span></span><br><span class="line">    print(<span class="string">&quot;平均市盈率:%.2f&quot;</span> % (factors.pe.mean()))</span><br><span class="line">    print(<span class="string">&quot;每股收益:%.2f&quot;</span> % (factors.esp.mean()))</span><br><span class="line">    print(<span class="string">&quot;每股净资产:%.2f&quot;</span> % (factors.bvps.mean()))</span><br><span class="line">    print(<span class="string">&quot;平均市净率:%.2f&quot;</span> % (factors.pb.mean()))</span><br><span class="line">    print(<span class="string">&quot;平均每股净利润:%.2f&quot;</span> % (factors.npr.mean()))</span><br><span class="line">    print(<span class="string">&quot;平均股东人数:%.2f&quot;</span> % (factors.holders.mean()))</span><br></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">平均市盈率:<span class="number">138.04</span></span><br><span class="line">每股收益:<span class="number">0.18</span></span><br><span class="line">每股净资产:<span class="number">5.24</span></span><br><span class="line">平均市净率:<span class="number">4.20</span></span><br><span class="line">平均每股净利润:<span class="number">13.38</span></span><br><span class="line">平均股东人数:<span class="number">54578.72</span></span><br></pre></td></tr></table></figure>
<p>画图看看。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 分析数据</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">analysis</span>(<span class="params">factors</span>):</span></span><br><span class="line">    print(<span class="string">&quot;平均市盈率:%.2f&quot;</span> % (factors.pe.mean()))</span><br><span class="line">    print(<span class="string">&quot;每股收益:%.2f&quot;</span> % (factors.esp.mean()))</span><br><span class="line">    print(<span class="string">&quot;每股净资产:%.2f&quot;</span> % (factors.bvps.mean()))</span><br><span class="line">    print(<span class="string">&quot;平均市净率:%.2f&quot;</span> % (factors.pb.mean()))</span><br><span class="line">    print(<span class="string">&quot;平均每股净利润:%.2f&quot;</span> % (factors.npr.mean()))</span><br><span class="line">    print(<span class="string">&quot;平均股东人数:%.2f&quot;</span> % (factors.holders.mean()))</span><br><span class="line">    <span class="comment"># 绘图</span></span><br><span class="line">    print(factors.pe)</span><br><span class="line">    plt.figure()</span><br><span class="line">    factors.pe.hist(bins = <span class="number">100</span>, <span class="built_in">range</span> = (<span class="number">0</span>, <span class="number">2.0</span>), align = <span class="string">&quot;left&quot;</span>)</span><br><span class="line">    plt.savefig(<span class="string">&quot;PE.png&quot;</span>)</span><br><span class="line">    plt.figure()</span><br><span class="line">    factors.esp.hist(bins = <span class="number">100</span>, <span class="built_in">range</span> = (<span class="number">0</span>, <span class="number">2.0</span>), align = <span class="string">&quot;left&quot;</span>)</span><br><span class="line">    plt.savefig(<span class="string">&quot;ESP.png&quot;</span>)</span><br><span class="line">    plt.figure()</span><br><span class="line">    factors.pb.hist(bins = <span class="number">100</span>, <span class="built_in">range</span> = (<span class="number">0</span>, <span class="number">50.0</span>), align = <span class="string">&quot;left&quot;</span>)</span><br><span class="line">    plt.savefig(<span class="string">&quot;PB.png&quot;</span>)</span><br><span class="line">    plt.figure()</span><br><span class="line">    factors.npr.hist(bins = <span class="number">100</span>, <span class="built_in">range</span> = (<span class="number">0</span>, <span class="number">50.0</span>), align = <span class="string">&quot;left&quot;</span>)</span><br><span class="line">    plt.savefig(<span class="string">&quot;NPR.png&quot;</span>)</span><br><span class="line">    plt.figure()</span><br><span class="line">    factors.holders.hist(bins = <span class="number">100</span>, <span class="built_in">range</span> = (<span class="number">0</span>, <span class="number">50.0</span>), align = <span class="string">&quot;left&quot;</span>)</span><br><span class="line">    plt.savefig(<span class="string">&quot;HOLDERS.png&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/58/02.png"><br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/58/03.png"><br>图形大多是这样的，长尾形的。值越高的股票越少。<br>现在来找因子了，我就主观定义吧：<br>选取市盈率、每股收益、每股净资产、市净率、净利润这几个指标，其中市盈率是越小越好，其它都是越大越好。因此设计的评分公式为：<br>评分 = -1×市盈率/平均市盈率 + 每股收益/平均每股收益 + 每股净资产/平均每股净资产 + 市净率/平均每股市净率 + 净利润/平均每股净利润<br>即把每个值都与所有值的平均值相除最后再相加。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 计算评分指标</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">scale</span>(<span class="params">factors</span>):</span></span><br><span class="line">    pe = -<span class="number">1.0</span>*factors.pe/factors.pe.mean()</span><br><span class="line">    esp = factors.esp/factors.esp.mean()</span><br><span class="line">    bvps = factors.bvps/factors.bvps.mean()</span><br><span class="line">    pb = factors.pb/factors.pb.mean()</span><br><span class="line">    npr = factors.npr/factors.npr.mean()</span><br><span class="line">    score = pe+esp+bvps+pb+npr</span><br><span class="line">    print(score)</span><br><span class="line">    <span class="comment"># 排序并画图</span></span><br><span class="line">    score = score.sort_values()</span><br><span class="line">    print(score)</span><br><span class="line">    score.plot(kind = <span class="string">&quot;hist&quot;</span>, bins = <span class="number">1000</span>, <span class="built_in">range</span> = (-<span class="number">25.0</span>, <span class="number">30.0</span>))</span><br><span class="line">    plt.savefig(<span class="string">&quot;fsctorScore.png&quot;</span>)</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/58/04.png"><br>提取评分最高的10个股票，结果如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Int64Index([<span class="number">661</span>, <span class="number">600695</span>, <span class="number">603301</span>, <span class="number">2582</span>, <span class="number">600620</span>, <span class="number">603444</span>, <span class="number">600061</span>, <span class="number">617</span>, <span class="number">2069</span>,</span><br><span class="line">            <span class="number">600519</span>],</span><br><span class="line">           dtype=<span class="string">&#x27;int64&#x27;</span>, name=<span class="string">&#x27;code&#x27;</span>)</span><br></pre></td></tr></table></figure>
<p>发现一个问题：661,2582这些是啥？唉，在一开始的筛选的代码里再加一条，排除代码小于100000的。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Int64Index([<span class="number">600895</span>, <span class="number">600621</span>, <span class="number">600674</span>, <span class="number">600685</span>, <span class="number">600695</span>, <span class="number">603301</span>, <span class="number">600620</span>, <span class="number">603444</span>,</span><br><span class="line">            <span class="number">600061</span>, <span class="number">600519</span>],</span><br><span class="line">           dtype=<span class="string">&#x27;int64&#x27;</span>, name=<span class="string">&#x27;code&#x27;</span>)</span><br></pre></td></tr></table></figure>
<p>现在就对了！<br>接下来就用这十只股票来回测，策略就是买入持有。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[<span class="string">&#x27;张江高科&#x27;</span> <span class="string">&#x27;华鑫股份&#x27;</span> <span class="string">&#x27;川投能源&#x27;</span> <span class="string">&#x27;中船防务&#x27;</span> <span class="string">&#x27;绿庭投 资&#x27;</span> <span class="string">&#x27;振德医疗&#x27;</span> <span class="string">&#x27;天宸股份&#x27;</span> <span class="string">&#x27;吉比特&#x27;</span> <span class="string">&#x27;国投资本&#x27;</span> <span class="string">&#x27;贵州茅台&#x27;</span>] [<span class="string">&#x27;600895&#x27;</span>, <span class="string">&#x27;600621&#x27;</span>, <span class="string">&#x27;600674&#x27;</span>, <span class="string">&#x27;600685&#x27;</span>, <span class="string">&#x27;600695&#x27;</span>, <span class="string">&#x27;603301&#x27;</span>, <span class="string">&#x27;600620&#x27;</span>, <span class="string">&#x27;603444&#x27;</span>, <span class="string">&#x27;600061&#x27;</span>, <span class="string">&#x27;600519&#x27;</span>]</span><br></pre></td></tr></table></figure>
<p>就这十只股票。<br>下面是回测代码:</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 交易策略类，一开始买入然后持有。</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">FactorStrategy</span>(<span class="params">bt.Strategy</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self</span>):</span></span><br><span class="line">        self.p_value = self.broker.getvalue()*<span class="number">0.9</span>/<span class="number">10.0</span></span><br><span class="line">       </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">next</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="comment"># 买入</span></span><br><span class="line">        <span class="keyword">for</span> data <span class="keyword">in</span> self.datas:</span><br><span class="line">            <span class="comment"># 获取仓位</span></span><br><span class="line">            pos = self.getposition(data).size</span><br><span class="line">            <span class="keyword">if</span> pos == <span class="number">0</span>:</span><br><span class="line">                size = <span class="built_in">int</span>(self.p_value/<span class="number">100</span>/data.close[<span class="number">0</span>])*<span class="number">100</span></span><br><span class="line">                self.buy(data = data, size = size)</span><br><span class="line">        <span class="comment"># 最后卖出</span></span><br><span class="line">        date = self.datas[<span class="number">0</span>].datetime.date(<span class="number">0</span>)</span><br><span class="line">        closeDate = datetime.datetime(<span class="number">2020</span>, <span class="number">7</span>, <span class="number">2</span>)</span><br><span class="line">        <span class="keyword">if</span> date.year == closeDate.year <span class="keyword">and</span> date.month == closeDate.month <span class="keyword">and</span> date.day == closeDate.day:</span><br><span class="line">            <span class="keyword">for</span> data <span class="keyword">in</span> self.datas:</span><br><span class="line">                pos = self.getposition(data).size</span><br><span class="line">                <span class="keyword">if</span> pos != <span class="number">0</span>:</span><br><span class="line">                    self.sell(data = data, size = pos )</span><br><span class="line">               </span><br><span class="line">    <span class="comment"># 输出</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">log</span>(<span class="params">self, txt</span>):</span></span><br><span class="line">        print(txt)</span><br><span class="line">       </span><br><span class="line">    <span class="comment"># 输出交易过程</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__displayOrder</span>(<span class="params">self, buy, order</span>):</span></span><br><span class="line">        <span class="keyword">if</span> buy:</span><br><span class="line">            self.log(</span><br><span class="line">                    <span class="string">&#x27;执行买入, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                    (order.executed.price,</span><br><span class="line">                     order.executed.value,</span><br><span class="line">                     order.executed.comm))</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            self.log(</span><br><span class="line">                    <span class="string">&#x27;执行卖出, 价格: %.2f, 成本: %.2f, 手续费 %.2f&#x27;</span> %</span><br><span class="line">                    (order.executed.price,</span><br><span class="line">                     order.executed.value,</span><br><span class="line">                     order.executed.comm))</span><br><span class="line">               </span><br><span class="line">    <span class="comment"># 交易情况</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">notify_order</span>(<span class="params">self, order</span>):</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Submitted, order.Accepted]:</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        <span class="keyword">if</span> order.status <span class="keyword">in</span> [order.Completed]:</span><br><span class="line">            <span class="keyword">if</span> order.isbuy():</span><br><span class="line">                self.__displayOrder(<span class="literal">True</span>, order)</span><br><span class="line">            <span class="keyword">elif</span> order.issell():</span><br><span class="line">                self.__displayOrder(<span class="literal">False</span>, order)</span><br><span class="line">        self.order = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    factors = getFactors()</span><br><span class="line">    analysis(factors)</span><br><span class="line">    score = scale(factors)</span><br><span class="line">    codes = score[-<span class="number">10</span>:].index</span><br><span class="line">    <span class="comment"># 进行回测</span></span><br><span class="line">    start = <span class="string">&quot;2018-01-01&quot;</span></span><br><span class="line">    end = <span class="string">&quot;2020-07-05&quot;</span></span><br><span class="line">    name = factors.loc[codes, <span class="string">&quot;name&quot;</span>].values</span><br><span class="line">    <span class="comment"># 将汉字转换为拼音</span></span><br><span class="line">    p = Pinyin()</span><br><span class="line">    name = [p.get_pinyin(s) <span class="keyword">for</span> s <span class="keyword">in</span> name]</span><br><span class="line">    code = [<span class="built_in">str</span>(x) <span class="keyword">for</span> x <span class="keyword">in</span> codes]</span><br><span class="line">    print(<span class="built_in">len</span>(name), code)</span><br><span class="line">    backtest = backtest.BackTest(FactorStrategy, start, end, code, name, <span class="number">1000000</span>, bDraw = <span class="literal">True</span>)</span><br><span class="line">    result = backtest.run()</span><br><span class="line">    backtest.output()</span><br><span class="line">    print(result)</span><br></pre></td></tr></table></figure>
<p>结果<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/58/05.png"><br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/58/06.png"></p>
<p>结果还不错，年化收益率15.8%，最大回撤达41.6%。夏普值0.44。有个问题，我用的因子数据应该是最近的，而回测时间是2018-2020年的，也就是用了未来数据。原因是我不知道怎么获取历史的因子数据，先掌握方法吧。还有画的图很烂，我再研究下。<br>代码地址还是： <a target="_blank" rel="noopener" href="https://github.com/zwdnet/MyQuant/tree/master/47">https://github.com/zwdnet/MyQuant/tree/master/47</a><br>策略文件为facts.py。</p>
<p>我发文章的三个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章地址： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/Backtrader/" rel="tag"># Backtrader</a>
          
            <a href="/tags/%E5%A4%9A%E5%9B%A0%E5%AD%90%E9%80%89%E8%82%A1/" rel="tag"># 多因子选股</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/08/14/%E4%BD%A0%E7%9F%A5%E9%81%93%E6%A0%91%E8%84%82%E7%B2%98%E6%8E%A5%E5%BC%8F%E5%9B%BA%E5%AE%9A%E6%A1%A5%E5%90%97%EF%BC%9F%E2%80%94%E2%80%94%E9%94%90%E8%AF%BB%E4%BC%9A%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B001/" rel="next" title="你知道树脂粘接式固定桥吗？——锐读会课程笔记01">
                <i class="fa fa-chevron-left"></i> 你知道树脂粘接式固定桥吗？——锐读会课程笔记01
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/08/29/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B086%E2%80%94%E2%80%94%E5%AE%9E%E7%8E%B0%E9%87%8F%E5%8C%96%E4%BA%A4%E6%98%93%E7%BB%8F%E5%85%B8%E7%AD%96%E7%95%A5-%E5%A4%9A%E5%9B%A0%E5%AD%90%E9%80%89%E8%82%A1%EF%BC%88%E6%94%B9%E8%BF%9B1%EF%BC%89/" rel="prev" title="量化投资学习笔记86——实现量化交易经典策略:多因子选股（改进1）">
                量化投资学习笔记86——实现量化交易经典策略:多因子选股（改进1） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
